package com.minelx.landisk.filesystem.core;

import com.minelx.landisk.filesystem.core.init.*;
import com.minelx.util.IOUtil;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.file.StandardOpenOption;

import static com.minelx.util.IOUtil.stringOf;

public class File {

	private final Path path;

	private File(Path path) {
		this.path = path;
	}

	public Path path() {
		return path;
	}

	public String read(Charset charset) throws IOException {
		try (InputStream source = inputStream()) {
			return stringOf(source, charset);
		}
	}

	public boolean empty() {
		try (InputStream inputStream = inputStream()) {
			return inputStream.read() == -1;
		} catch (IOException e) {
			throw new FileAccessingException("can't read bytes from file.", e);
		}
	}

	public void write(InputStream inputStream) throws IOException {
		OutputStream output = outputStream(StandardOpenOption.CREATE);
		IOUtil.exchange(inputStream, output);
		output.flush();
		output.close();
	}

	public void write(String content, Charset charset) throws IOException {
		write(new ByteArrayInputStream(content.getBytes(charset)));
	}

	public InputStream inputStream() {
		return path.getPathMethodProvider().openInputStream();
	}

	public OutputStream outputStream(StandardOpenOption openOption) {
		return path.getPathMethodProvider().openOutputStream(openOption);
	}

	public boolean isExtensionOf(String extension) {
		return path.name().endsWith("." + extension);
	}

	public static File create(Path path, OpenPolicy openPolicy) {
		openPolicy.open(path, PathType.FILE);
		return new File(path);
	}
}
